var app = getApp()
var auth = require('../../lib/auth/login')
var tools = require('../../lib/system/tools')
var pages = require('../../lib/common/pageConstant')
var qrCode = require('../../lib/system/qrcode')
var commonConstant = require('../../lib/common/constant')

var orderStatusRules = {
    'all': '',
    'waiting': '0',
    'during': '1',
    'finished': '2',
}

Page({
    data: {
        tabbarType: {
            type: 'center'
        },
        tabType: 'personal',
        commonConstant: commonConstant,
        orderTabbar: 'all',
        userDetail: {
            name: '买家买买买买买',
            app_user_photo: '##',
            //weapp_role_id: '6d407bbc66c340a48e885b9b9fc6ca01'
            weapp_role_id: 'eb475d9a3e8c407fabf3048f5fba404d'
        },
        userRole: '',
        userPoint: 0,
        userBalance: 0,
        userCoupon: 0,
        userVip: '',
        orderList: [
            {
                "changed_by": "王岩",
                "changed_on": "2017-11-02T15:05:26",
                "checkout_datetime": "2017-11-03T23:03:29",
                "created_by": "王岩",
                "created_on": "2017-11-02T15:05:26",
                "enable": true,
                "id": "1b36e0b648ec45a396f9c538038025ad",
                "payment_datetime": "2017-11-03T23:03:29",
                "payment_method": "线上支付",
                "qr_code": null,
                "quantity": 1,
                "settlement_price": 58,
                "snapshot": "{\"summary\":58}",
                "status": 1,
                "user_coupon_id": null,
                "weapp_logistics_location": "测试物流点1",
                "weapp_logistics_location_id": "f70b1dff-b992-11e7-9d11-000c2951e0ca",
                "weapp_product_distribution": "自提",
                "weapp_product_distribution_id": "1201688145064b1c9130630cbf312911",
                "weapp_user": "测试小程序用户",
                "weapp_user_id": "3027de32fc4141dbbefd3ad24a7d7ec4"
            }
        ]
    },
    //事件处理函数
    bindViewTap: function () {
        wx.navigateTo({
            url: '../logs/logs'
        })
    },
    onLoad: function () {
    },
    onShow: function () {
        var that = this
        tools.requestWithAuth({
            url: 'profile',
            feedback: {
                success: data => {
                    console.log(data)
                    that.setData({
                        userDetail: data
                    })
                }
            }
        })
        tools.requestWithAuth({
            url: 'bonus_point',
            feedback: {
                success: data => {
                    console.log(data)
                    that.setData({
                        userPoint: data.current_bonus_point
                    })
                }
            }
        })
        tools.requestWithAuth({
            url: 'vip',
            feedback: {
                success: data => {
                    console.log(data)
                    that.setData({
                        userVip: data.weapp_vip
                    })
                }
            }
        })
        this.setData({
            orderTabbar: 'all',
            tabType: 'personal'
        })
        this.showOrders('all')
    },
    showConsumerOrders: function (orderType) {
        var orderStatus = orderStatusRules[orderType]
        var requestParams = {}
        var that = this
        if (orderStatus) {
            requestParams['status'] = orderStatus
        }
        tools.requestWithAuth({
            url: 'saler_order',
            data: requestParams,
            feedback: {
                success: orderData => {
                    console.log(orderData)
                    var showQrCodeBtn = false
                    var that = this
                    if (that.data.tabType == 'personal') {
                        showQrCodeBtn = true
                    }
                    for (var k in orderData) {
                        orderData[k]['snapshot'] = JSON.parse(orderData[k]['snapshot'])
                        orderData[k]['snapshot']['description'] = orderData[k]['snapshot']['description'].replace(/\n/, '')
                        if (orderData[k]['status'] == 1 && showQrCodeBtn) {
                            orderData[k]['showQrCodeBtn'] = true
                        }
                    }
                    that.setData({
                        orderList: orderData
                    })
                }
            }
        })
    },
    showOrders: function (orderType) {
        var orderStatus = orderStatusRules[orderType]
        var requestParams = {}
        var that = this
        if (orderStatus) {
            requestParams['status'] = orderStatus
        }
        tools.requestWithAuth({
            url: 'user_order',
            data: requestParams,
            feedback: {
                success: orderData => {
                    console.log(orderData)
                    var showQrCodeBtn = false
                    var that = this
                    if (that.data.tabType == 'personal') {
                        showQrCodeBtn = true
                    }
                    for (var k in orderData) {
                        orderData[k]['snapshot'] = JSON.parse(orderData[k]['snapshot'])
                        orderData[k]['snapshot']['description'] = orderData[k]['snapshot']['description'].replace(/\n/, '')
                        if (orderData[k]['status'] == 1 && showQrCodeBtn) {
                            orderData[k]['showQrCodeBtn'] = true
                        }
                    }
                    that.setData({
                        orderList: orderData
                    })
                }
            }
        })
    },
    getUserInfo: function (e) {
        console.log(e)
        app.globalData.userInfo = e.detail.userInfo
        this.setData({
            userInfo: e.detail.userInfo,
            hasUserInfo: true
        })
    },
    changeTabType: function (event) {
        var tabType = event.currentTarget.dataset.tag
        if (tabType == 'consumer') {
            this.showConsumerOrders('all');
        } else {
            this.showOrders('all');
        }
        this.setData({
            orderTabbar: 'all',
            tabType: tabType
        })
    },
    tabClick: function (event) {
        console.log(event)
        var tagFlag = event.currentTarget.dataset.tag
        this.setData({
            orderTabbar : tagFlag
        }) 
        if (this.data.tabType == 'consumer') {
            this.showConsumerOrders(tagFlag);
        } else {
            this.showOrders(tagFlag)
        }
    },
    callScaner: function (event) {
        var that = this
        wx.scanCode({
            success: function (res) {
                var orderId = res.result
                wx.navigateTo({
                    url: pages.confirmPage + '?order_id=' + orderId
                })
                console.log(res)
            }
        })
    },
    requestPayment: function (signInfo, callback) {
        wx.requestPayment({
            timeStamp: signInfo.timeStamp,
            nonceStr: signInfo.nonceStr,
            package: signInfo.package,
            signType: signInfo.signType,
            paySign: signInfo.paySign,
            success: function (res) {
                console.log(res)
                callback(signInfo)
            },
            fail: function (res) {
                console.log(res)
            }
        })
    },
    changeOrder: function (event) {
        var orderId = event.currentTarget.dataset.order_id
        var orderStatus = event.currentTarget.dataset.order_stat
        var that = this
        if (orderStatus != 0 || this.data.tabType != 'personal') {
            return false
        }
        tools.requestWithAuth({
            url: 'continue_order',
            method: 'POST',
            data: {
                order_id: orderId
            },
            feedback: {
                success: data => {
                    that.requestPayment(data, function (res) {
                        tools.requestWithAuth({
                            url: 'pay_order',
                            method: 'PUT',
                            data: {
                                order_id: orderId
                            },
                            feedback: {
                                success: dt => {
                                    wx.reLaunch({
                                        url: pages.homePage
                                    })
                                }
                            }
                        })
                    })
                }
            }
        })
    },
    previewOrderQrcode: function (event) {
        var orderId = event.currentTarget.dataset.order_id
        var qrImg = qrCode.getQRCodeImg(orderId)
        wx.previewImage({
            current: qrImg, // 当前显示图片的http链接
            urls: [
                qrImg
            ] // 需要预览的图片http链接列表
        })
    }
})
